package com.recharge.callback;

import com.recharge.domain.TradeMerchant;
import com.recharge.domain.TradeOrder;
import com.recharge.utils.HttpClientUtils;
import com.recharge.utils.OrderStatus;
import com.recharge.utils.ProcessResult;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created by CAOQI on 2017/1/8.
 */
@Service
public class ApiCallBackService extends AbsCallBackService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public ProcessResult callBack(TradeOrder tradeOrder,TradeMerchant tradeMerchant) {

        ProcessResult processResult = new ProcessResult();

        String sessionId = tradeOrder.getOrderId();
        String coopOrderStatus = "";
        String failCode = "";
        String failDesc = "";

        processResult.setCode(ProcessResult.SUCCESS);

//        说明是一个正常的回调
        if (tradeOrder.getTmStatus() ==null){
            if (StringUtils.equals(tradeOrder.getOrderStatus()+"", OrderStatus.SUCCESS+"")) {
                coopOrderStatus = "SUCCESS";
                processResult.setCode(ProcessResult.SUCCESS);
            } else if (StringUtils.equals(tradeOrder.getOrderStatus() + "", OrderStatus.FAIL + "")) {
                coopOrderStatus = "FAILED";
                processResult.setCode(ProcessResult.FAIL);
                failCode = "9999";//notifyVo.getChargeStatus();
                failDesc = "unkownerror";
            } else {
                logger.info("orderId=" + sessionId + "|非成功和失败的状态");
                processResult.setCode(ProcessResult.FAIL);
                return processResult;
            }
        }else{
//            手动回调的，按照数据库里面的来
            if (tradeOrder.getTmStatus()==0) {
                coopOrderStatus = "SUCCESS";
                processResult.setCode(ProcessResult.SUCCESS);
            } else if (tradeOrder.getTmStatus()==3) {
                coopOrderStatus = "FAILED";
                processResult.setCode(ProcessResult.FAIL);
                failCode = "9999";//notifyVo.getChargeStatus();
                failDesc = "unkownerror";
            } else {
                logger.info("orderId=" + sessionId + "|非成功和失败的状态");
                processResult.setCode(ProcessResult.FAIL);
                return processResult;
            }
        }



        Date date = new Date();
        // SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String ts = Long.toString(date.getTime());
        String coopOrderNo = tradeOrder.getOrderId();
        String supplierId = tradeOrder.getMerId();
        String tbOrderNo = tradeOrder.getMerOrderid();

        String signstr = "coopOrderNo" + coopOrderNo + "coopOrderStatus" + coopOrderStatus;
        if (!"".equals(failCode)) {
            signstr = signstr + "failCode" + failCode + "failDesc" + failDesc;
        }
        signstr = signstr + "supplierId" + supplierId + "merOrderNo" + tbOrderNo + "ts" + ts;
        String sign = "";
        try {
            sign = DigestUtils.md5Hex(signstr + tradeMerchant.getMd5Key());
        } catch (Exception e1) {
            logger.info("session=" + sessionId + "|Md5Util.getMD5异常: " + e1.getMessage());
            processResult.setCode(ProcessResult.UNKNOWN);
            return processResult;
        }
        String sendData = "coopOrderNo=" + tradeOrder.getOrderId() + "&coopOrderStatus=" + coopOrderStatus +
                "&failCode=" + failCode + "&failDesc=" + failDesc + "&supplierId="
                + tradeOrder.getMerId() + "&merOrderNo=" + tradeOrder.getMerOrderid() + "&ts=" + ts + "&sign=" + sign;

        logger.info("session=" + sessionId + "|通知充值结果到下游, sendData=" + sendData);

        String result = null;
        try {
            result = HttpClientUtils.invokeGetHttp(tradeOrder.getNotifyUrl() + "?" + sendData, "utf-8", 2000);
        } catch (Exception e) {
            logger.error("call back to merchant fail",e);
        }

        logger.info("session=" + sessionId + "|收到下游返回数据, responseData=" + result);


        return processResult;
    }
}
